﻿using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.DTO;
using IMClient.View;
using IMClient.WebSocketService;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace IMClient.ViewModels
{
    public partial class LoginViewModel : ObservableObject
    {
        [ObservableProperty] private string loginUserId = string.Empty;

        [ObservableProperty] private string password = string.Empty;

        [ObservableProperty] private string? userIdError;

        [ObservableProperty] private string? passwordError;

        [ObservableProperty] private bool hasUserIdError;

        [ObservableProperty] private bool hasPasswordError;
        
        [RelayCommand]
        private async Task Login()
        {
            // 重置所有错误提示和边框颜色
            ResetErrors();

            // 检查用户ID格式
            if (string.IsNullOrEmpty(LoginUserId))
            {
                HasUserIdError = true;
                UserIdError = "(用户ID不能为空)";
                return;
            }
            else if (!Regex.IsMatch(LoginUserId, @"^\d{10}$"))
            {
                HasUserIdError = true;
                UserIdError = "(用户ID必须是10位数字)";
                return;
            }

            // 检查密码格式
            if (string.IsNullOrEmpty(Password))
            {
                HasPasswordError = true;
                PasswordError = "(密码不能为空)";
                return;
            }
            else if (!Regex.IsMatch(Password, @"^[a-zA-Z0-9]+$"))
            {
                HasPasswordError = true;
                PasswordError = "(密码只能包含字母和数字)";
                return;
            }

            // 发送登录请求
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var content =
                        new StringContent("{\"UserId\":\"" + LoginUserId + "\",\"Password\":\"" + Password + "\"}");
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var response = await client.PostAsync($"{NetWorkConfig.BaseUrl}/user/auth/login", content);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        // 解析 JSON
                        var jsonObject = JObject.Parse(json);

                        string userId = jsonObject["data"]?["userId"]?.ToString() ?? String.Empty;
                        string userName = jsonObject["data"]?["userName"]?.ToString() ?? String.Empty;
                        string avatar = jsonObject["data"]?["avatar"]?.ToString() ?? String.Empty;
                        string webSocketUrl = jsonObject["data"]?["webSocketUrl"]?.ToString() ?? String.Empty;

                        User.UserAvatar = !string.IsNullOrEmpty(avatar)
                            ? avatar
                            : // 将 avatar 字段赋值
                            "https://im-net.oss-cn-wuhan-lr.aliyuncs.com/default.png";

                        User.UserId = userId;
                        User.UserName = userName;
                        WebSocketConnection.WebSocketUrl = webSocketUrl;

                        if (WebSocketConnection.WS == null || WebSocketConnection.WS.State != WebSocketState.Open)
                        {
                            await WebSocketConnection.ConnectWebSocket();
                        }

                        // 启动消息接收任务
                        WebSocketConnection.StartReceivingMessages();

                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ChatWindow chatWindow = new ChatWindow();
                            chatWindow.Show();

                            // 关闭所有RegisterWindow类型的窗口
                            foreach (Window window in Application.Current.Windows.Cast<Window>().ToList())
                            {
                                if (window.GetType().Name == "LoginWindow")
                                {
                                    window.Close();
                                }
                            }

                            // 设置新窗口为主窗口
                            Application.Current.MainWindow = chatWindow;
                        });

                        // 拉取好友列表和群列表
                        await UpdateFriendsFromServer(userId, client);

                        // 拉取离线消息
                        content = new StringContent("{\"UserId\":\"" + LoginUserId + "\"}");
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        response = await client.PostAsync($"{NetWorkConfig.BaseUrl}/message/unread", content);
                        // 解析 JSON
                        json = await response.Content.ReadAsStringAsync();
                        if (response.IsSuccessStatusCode)
                        {
                            return;
                        }

                        throw new Exception("拉取离线消息失败！");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void ResetErrors()
        {
            HasUserIdError = false;
            HasPasswordError = false;
            UserIdError = string.Empty;
            PasswordError = string.Empty;
        }

        private async Task UpdateFriendsFromServer(string userId, HttpClient httpClient)
        {
            try
            {
                var content = new StringContent(
                JsonSerializer.Serialize(new { UserId = userId }),
                    Encoding.UTF8,
                    "application/json");

                var response = await httpClient.PostAsync(
                    $"{NetWorkConfig.BaseUrl}/user/query/contacts",
                    content);

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var contactsResponse = JsonSerializer.Deserialize<ContactsResponse>(result);

                    if (contactsResponse?.Code == "0000" && contactsResponse.Data != null)
                    {
                        User.FriendList = contactsResponse.Data.Friends;
                        User.GroupList = contactsResponse.Data.Groups;
                        
                        User.UpdatedFromServer();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新好友列表失败: {ex.Message}");
            }
        }
    }
}